﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VFTray
{
    class ProcessCenter
    {
        internal MemoryState Status_Verified = new MemoryState(false);

		internal List<FeedTray> Feeders = new List<FeedTray>();

		public ProcessCenter()
        {
            GlobalParams.PC = this;
        }

		#region sequence_frame
		internal void Init()
		{
			int index = 0;
			foreach (var cfg in GlobalParams.CD.Trayes)
			{
				var f = new FeedTray(index, cfg.Name, cfg.SiteID);
				f.UpdateConfig(cfg);
				Feeders.Add(f);
				index++;
			}

			foreach (var f in Feeders)
			{
				f.Init();
			}
		}
		internal void Close()
        {
			ClosePhase1();
			System.Threading.Thread.Sleep(500);
			ClosePhase2();
		}

		private void ClosePhase2()
		{
			foreach(var f in Feeders)
				f.ClosePhase2();
		}

		private void ClosePhase1()
		{
			GlobalParams.CS.Close();
			foreach (var f in Feeders)
				f.ClosePhase1();
		}

		internal void Closed()
		{
			foreach (var f in Feeders)
				f.Closed();
			//if(CamUp!=null) CamUp.Close();
			//if (CamDown != null) CamDown.Close();
		}

		internal void UpdateCvParams()
		{
			
		}

		internal void updatemark()
		{
			bool resave = false;
			var rfn = GlobalParams.CD.GetRecipeFile();
			FileInfo crfi = new FileInfo(rfn);
			string cdir = crfi.DirectoryName;
			for (int i = 0; i < GlobalParams.CR.Steps.Count; i++)
			{
				string mf = GlobalParams.CR.Steps[i].vision1.mark_fn;
				if (!string.IsNullOrEmpty(mf))
				{
					FileInfo mi = new FileInfo(mf);
					string cmk = Path.Combine(cdir, mi.Name);
					if (File.Exists(cmk) && cmk != mf)
					{
						GlobalParams.CR.Steps[i].vision1.mark_fn = cmk;
						resave = true;
					}
				}

				mf = GlobalParams.CR.Steps[i].vision2.mark_fn;
				if (!string.IsNullOrEmpty(mf))
				{
					FileInfo mi = new FileInfo(mf);
					string cmk = Path.Combine(cdir, mi.Name);
					if (File.Exists(cmk) && cmk != mf)
					{
						GlobalParams.CR.Steps[i].vision2.mark_fn = cmk;
						resave = true;
					}
				}
			}
			if(resave) GlobalParams.CRF.Save();
		}

		internal bool UpdateRecipe(string rn)
		{
			if (string.IsNullOrEmpty(rn))//load from CD.RecipeName;
			{
				return false;
			}
			else
			{
				string dir = Path.Combine(GlobalParams.CD.RecipeBootPath, rn);
				if (!Directory.Exists(dir)) return false;

				string fn = Path.Combine(dir, rn + ".xml");
				if (!File.Exists(fn)) return false;

				try
				{
					var crf = ConfigUtility.ConfigurationBase<Config.ConfigurationRecipe>.Load(fn);
					GlobalParams.CRF = crf;
					GlobalParams.CR = crf.CFG;
					GlobalParams.CD.RecipeName = rn;
					GlobalParams.CDF.Save();
				}
				catch (Exception ex)
				{
					LogUtility.LOG.Error("UpdateRecipe", ex);
					return false;
				}
			}
			updatemark();

			UpdateCvParams();
			return true;
		}
		#endregion sequence_frame
	}
}
